package com.company;
import java.io.*;
import java.net.Socket;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class RequestHandle implements Runnable{
    private String indexFileName = "index.html";
    private Socket socket;
    private OutputStream output;
    private InputStream input;
    public RequestHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            output = socket.getOutputStream();
            Writer writer = new BufferedWriter(new OutputStreamWriter(output));
            input = socket.getInputStream();

            String temp;
            StringBuilder sb = new StringBuilder("");
            String firstRequest;
            int c;
            while (true) {
                c = input.read();
                if (c == '\r' || c == '\n') {
                    break;
                }
                sb.append((char)c);
            }
            firstRequest = sb.toString();
            System.out.println(firstRequest);

            String[] tokens = firstRequest.split("\\s+");
            String method = tokens[0];
            String version = "";
            if(method.equals("GET")) {
                String fileName = tokens[1];
                if (fileName.endsWith("/")) {
                    fileName += indexFileName;
                }
                String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName);
                if (tokens.length > 2) {
                    version = tokens[2];
                }
                File file = new File(fileName.substring(1,fileName.length()));
                byte[] content = Files.readAllBytes(file.toPath());
                sendHeaderToClient(writer, "HTTP/1.0 200 OK", contentType, content.length);
                output.write(content);
                output.flush();
            } else if (method.equals("HEAD")) {
                sendHeaderToClient(writer, "HTTP/1.0 200 OK", "text/html", 0);
            } else if (method.equals("POST")) {
                StringBuilder ss = new StringBuilder("");
                while(true) {
                   c = input.read();
                   ss.append((char)c).toString();
                   if(ss.toString().split("&").length == 3) {
                        break;
                    }
                }
                int start = ss.indexOf("username");
                int end = ss.lastIndexOf("&");
                String content = ss.substring(start, end);
                System.out.println(content);
                Map<String, String> contentMap = new HashMap<>();
                String s1[] = content.split("&");
                String ss1[] = s1[0].split("=");
                String ss2[] = s1[1].split("=");
                contentMap.put(ss1[0], URLDecoder.decode(ss1[1], "utf-8"));
                contentMap.put(ss2[0], URLDecoder.decode(ss2[1], "utf-8"));
                System.out.println(contentMap);

                String body = new StringBuilder("<HTML>\r\n")
                        .append("<HEAD><meta charset=\"utf-8\"><TITLE>Login successfully</TITLE>\r\n")
                        .append("<HEAD>\r\n")
                        .append("<BODY>")
                        .append("<H1>your username:" + contentMap.get("username") + "\n your password:" + contentMap.get("password") + "</H1>\r\n")
                        .append("</BODY></HTML>\r\n")
                        .toString();
                sendHeaderToClient(writer, "HTTP/1.0 200 OK", "text/html, charset=utf-8", body.length());
                writer.write(body);
                writer.flush();

            } else if (method.equals("PUT")) {
                int length = 0;
                byte[] bytes;
                while (true) {
                    c = input.read();
                    sb.append((char) c);
                    if(sb.toString().contains("content-length") && sb.toString().contains("Connection: keep-alive\r\n\r\n")) {

                        temp = sb.substring(sb.toString().indexOf("content-length") + 16, sb.toString().indexOf("Connection: keep-alive") - 2);
                        bytes = new byte[Integer.parseInt(temp)];
                        while ( length < Integer.parseInt(temp)) {
                            c = input.read(bytes, length,Integer.parseInt(temp)-length );
                            length += c;
                        }
                        break;
                    }
                }
                System.out.println(length);
                File file = new File("xx.pdf" );
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(bytes);
                fileOutputStream.close();

                sendHeaderToClient(writer,"HTTP/1.0 200 OK", "text/html", length);
            }
        }catch (IOException e) {

        }finally {
            if(input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void sendHeaderToClient(Writer writer, String responseCode, String contentType, int length) throws IOException{
        writer.write(responseCode + "\r\n");
        writer.write("Date:" + new Date() + "\r\n");
        writer.write("Server:  JavaHTTP 1.0 \r\n");
        writer.write("Content-length: " + length + "\r\n");
        writer.write("Content-type: " + contentType + "\r\n\r\n");
        writer.flush();
    }
}
